package sk.naive.talker.tcpadapter;

import java.util.regex.*;
import java.util.*;

/**
 * AnsiUtils.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.3 $ $Date: 2004/10/24 16:57:06 $
 */
public class AnsiUtils {
	public static final String ERASE_DISPLAY = "\033[2J";
	public static final String SET_WRAP_LINES = "\033[=7h";

	public static final String HOME(int line, int col) {
		return "\033[" + line + ";" + col + "H";
	}

	private static Pattern ansiPattern = Pattern.compile("\\033\\[(?:" +
		"2J|" +
		"=7h|" +
		"\\d+;\\d+H|" +
		"[\\d;]+m" +
		")|$");

	public static int length(String s) {
		int len = 0;
		int last = 0;
		Matcher m = ansiPattern.matcher(s);
		while (m.find()) {
			len += m.start() - last;
			last = m.end();
		}
		return len;
	}

	public static List splitLines(String s, int lineLen) {
		List lines = new ArrayList();
		int len = 0;
		int lastMatchEnd = 0;
		int lastLineEnd = 0;
		Matcher m = ansiPattern.matcher(s);
		while (m.find()) {
			len += m.start() - lastMatchEnd;
			while (len > lineLen) {
				len = len - lineLen;
				int lineEndPos = m.start() - len;
				lines.add(s.substring(lastLineEnd, lineEndPos));
				lastLineEnd = lineEndPos;
			}
			lastMatchEnd = m.end();
		}
		lines.add(s.substring(lastLineEnd));
		return lines;
	}
}
